<?php

namespace App\Http\Controllers\Api;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\Post;
use App\Models\Comment;
use App\Http\Resources\PostResource;
use App\Http\Resources\CommentResource;
use App\Http\Requests\PostRequest;
use App\Http\Requests\CommentRequest;

class CommentController extends Controller
{
    
    
    public function like($id,Request $request){
        $user = $request->user();
        if( !$user ) return response()->json( ['err'=>1, 'msg'=>'请先进行登录','url'=>'/pages/sign/login', 'err_msg'=>'用户未登录请先进行登录'] );
        $data = Comment::findOrFail($id);
        if(!$user->hasLiked($data)){
            $user->like($data);
            $data->liked ++;
            // 排序等于喜欢人数+认同人数+否定人数(暂时性的)
            $mt_time =  strtotime( $data->created_at->format('Y-m-d') ) - strtotime('2019-05-01');
            $data->rank = $this->rank( $data->liked, $data->commented, $mt_time);
            $data->save();
        }
        return response()->json(['ok']);
    }
    
    public function unlike($id,Request $request){
        $user = $request->user();
        if( !$user ) return response()->json( ['err'=>1, 'msg'=>'请先进行登录','url'=>'/pages/sign/login', 'err_msg'=>'用户未登录请先进行登录'] );
        $data = Comment::findOrFail($id);
        if($user->hasLiked($data)){
            $user->unlike($data);
            $data->liked --;
            // 排序等于喜欢人数+认同人数+否定人数(暂时性的)
            // 间隔
            $mt_time =  strtotime( $data->created_at->format('Y-m-d') ) - strtotime('2019-05-01');
            $data->rank = $this->rank( $data->liked, $data->commented, $mt_time);
            $data->save();
        }
        return response()->json(['ok']);
    }

     /**
     * 实现近期热门排序 （自己去了解这个算法有什么用）
     * @param int $vote 支持
     * @param int $devote 反对
     * @param bool $time  创建项目时间差 
     * @return float
     */
    function rank($liked = 100, $commented = 99, $time = false){
        $socre = log10($liked + $commented *2 ) +  $time / 86400; // 建议值为 45000;
        return intval($socre * 1000);
    }
}
